package com.example.controller;

import com.example.pojo.Course;
import com.example.pojo.Grade;
import com.example.pojo.Request;
import com.example.pojo.Student;
import com.example.service.AdminService;
import com.example.service.StudentService;
import com.example.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ author:lin tingfeng
 * @ data:2021/9/6-22:55
 */
@Controller
public class IndexController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private AdminService adminService;


    private Integer number = 0;
    private Integer proxy;
    private Integer stuPower = 0;
    private Integer gradePower = 0;
    private Integer reportPower = 0;
    private static Student staticStudent = null;
//    private static Map<Integer,String> map = null;
//    private File file =new File("审核内容");
//    private FileWriter fw = null;

    /**************
     ****登录验证****
     **************/
    @RequestMapping("/index")

    public String index(@RequestParam("account") String account, @RequestParam("password") String password, Model model, HttpSession session) {
        if (studentService.validateLogin(account, password)) {
            session.setAttribute("loginUser", account);
            session.setAttribute("loginUserpw", password);
            model.addAttribute("loginUser", account);
            number = 1;
            proxy = 0;
            String power = studentService.selectStudentById(account).getPower();
            if (power.equals("学生管理"))
                stuPower = 1;
            else if (power.equals("成绩管理"))
                gradePower = 1;
            else if (power.equals("Excel导出"))
                reportPower = 1;
            return "student";
        } else if (adminService.validateLogin(account, password)) {
            session.setAttribute("loginUser", account);
            session.setAttribute("loginUserpw", password);
            model.addAttribute("loginUser", account);
            number = 2;
            proxy = 1;
            return "index";
        } else {
            model.addAttribute("msg", "用户名或者密码错误！");
            return "login";
        }

    }
/************************************************************************************/
/************************************************************************************/

    /******************
     ****学生信息列表****
     ******************/
    @GetMapping("/managementStudent")
//    @ResponseBody
    public String managementStudent(Model model) {
        model.addAttribute("message", studentService.selectStudentByAll());
        return "managementStudent";
    }

    /**************
     **添加学生信息**
     **************/
    @RequestMapping("/index/insert")
//    @ResponseBody
    public String insert(HttpServletRequest request, Model model) {
        if (proxy == 1 || stuPower == 1) {
            Student student = redirtRequest(request);
            if (student != null) {
                if (studentService.selectStudentById(student.getStuid()) == null && studentService.insertStudent(student)) {
                    model.addAttribute("message", studentService.selectStudentByAll());
                    model.addAttribute("path", "/managementStudent");
                    model.addAttribute("msg", "学生信息添加成功！！！");
                    return "success";
                }
            }
            model.addAttribute("path", "/managementStudent");
            model.addAttribute("msg", "学生信息添加失败，请重新编辑完善并保证编辑信息正确！");
            return "fail";
        } else {
            model.addAttribute("path", "/managementStudent");
            model.addAttribute("msg", "对不起，您的权限不够！!");
            return "fail";
        }
    }

    /**************
     **更新学生信息**
     **************/
    @GetMapping("/updateStudent/{stuid}")
    public String update(@PathVariable("stuid") String stuid, Model model) {
        Student student = studentService.selectStudentById(stuid);
        model.addAttribute("stu", student);
        return "updateStudent";
    }

    @RequestMapping("/index/update")
//    @ResponseBody
    public String updateStudent(Model model, HttpServletRequest request) {
        if (proxy == 1 || stuPower == 1) {
            Student student = redirtRequest(request);
            if (student != null) {
                model.addAttribute("stu", student);
                if (studentService.updateStudent(student)) {
                    model.addAttribute("path", "/managementStudent");
                    model.addAttribute("msg", "学生信息更新成功！！！");
                    return "success";
                }
            }
            model.addAttribute("path", "/managementStudent");
            model.addAttribute("msg", "学生信息更新失败，请重新编辑完善并保证编辑信息正确！");
            return "fail";
        } else {
            model.addAttribute("path", "/managementStudent");
            model.addAttribute("msg", "对不起，您的权限不够！!");
            return "fail";
        }
    }

    /**************
     **删除学生信息**
     **************/
    @RequestMapping("/index/delete/{stuid}")
//    @ResponseBody
    public String deleteStudent(@PathVariable("stuid") String stuid, Model model) {
        if (proxy == 1 || stuPower == 1) {
            if (studentService.selectStudentById(stuid) != null && studentService.deleteStudentById(stuid)) {
                model.addAttribute("path", "/managementStudent");
                model.addAttribute("msg", "学生信息更新成功！！！");
                return "success";
            }
            model.addAttribute("path", "/managementStudent");
            model.addAttribute("msg", "学生信息更新失败，数据异常！");
            return "fail";
        } else {
            model.addAttribute("path", "/managementStudent");
            model.addAttribute("msg", "对不起，您的权限不够！!");
            return "fail";
        }
    }

    /**************
     **查询学生信息**
     **************/
    @RequestMapping("/index/select")
//    @ResponseBody
    public String selectStudent(HttpServletRequest request, Model model) {
        String type = request.getParameter("type");
        String content = request.getParameter("content");
        List<Student> list = studentService.selectStudentByType(type, content);
        if (list != null)
            model.addAttribute("message", list);
        return "managementStudent";
    }

    /**************
     **查询个人信息**
     **************/
    @RequestMapping("/personalInformation")
//    @ResponseBody
    public String personalInformation(Model model, HttpServletRequest request) {
        Object stuid = request.getSession().getAttribute("loginUser");
        Student student = studentService.selectStudentById((String) stuid);
//        model.addAttribute("message", student);
        model.addAttribute("stuid", student.getStuid());
        model.addAttribute("name", student.getName());
        model.addAttribute("sex", student.getSex());
        model.addAttribute("password", student.getPassword());
        model.addAttribute("power", student.getPower());
        List<Request> list = adminService.selectRequestByAll();
        List<Request> newList = new ArrayList<>();
        for (Request r : list
        ) {
            if (r.getStuid().equals(student.getStuid()) && r.getProblem().equals("更新个人信息")) {
                newList.add(r);
            }
        }
        if (newList.size() != 0) {
            model.addAttribute("status", newList.get(newList.size() - 1).getStatus());
            if (newList.get(newList.size() - 1).getStatus().equals("正在审核") || newList.get(newList.size() - 1).getStatus().equals("撤销审核"))
                model.addAttribute("color", "color:red");
            else if (newList.get(newList.size() - 1).getStatus().equals("审核通过"))
                model.addAttribute("color", "color:green");
        } else {
            model.addAttribute("status", "未提交修改请求");
            model.addAttribute("color", "color:grey");
        }
        return "personalInformation";
    }

    /**************
     **更新个人信息**
     **************/
    @RequestMapping("/personalInformation/update")
    public String personalInformationUpdate(Model model, HttpServletRequest request) {
        Student updateStudent = redirtRequest(request);
        Student oldStudent = studentService.selectStudentById(updateStudent.getStuid());
        if (updateStudent != null) {
            Request r = new Request(updateStudent.getStuid(), studentService.selectStudentById(updateStudent.getStuid()).getName(), "更新个人信息", new Date(), "正在审核", updateStudent.getStuid() + "@qq.com");
            if (adminService.selectRequestById(r.getId()) == null && adminService.insertRequest(r) != null) {
                model.addAttribute("path", "/personalInformation");
                model.addAttribute("msg", "您的申诉请求已受理，请耐心等待系统回复！！！");
                staticStudent = updateStudent;
//                try {
//                    fw = new FileWriter(file);
//                    fw.write(oldStudent.getStuid()+"===>"+updateStudent.getStuid()+"\r\n");
//                    fw.write(oldStudent.getName()+"===>"+updateStudent.getName()+"\r\n");
//                    fw.write(oldStudent.getSex()+"===>"+updateStudent.getSex()+"\r\n");
//                    fw.write(oldStudent.getPower()+"===>"+updateStudent.getPower()+"\r\n");
//                    fw.write(oldStudent.getPassword()+"===>"+updateStudent.getPassword()+"\r\n");
//                    fw.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }

//                map = new HashMap<>();
//                map.put(1,oldStudent.getStuid()+"===>"+updateStudent.getStuid());
//                map.put(2,oldStudent.getName()+"===>"+updateStudent.getName());
//                map.put(3,oldStudent.getSex()+"===>"+updateStudent.getSex());
//                map.put(4,oldStudent.getPower()+"===>"+updateStudent.getPower());
//                map.put(5,oldStudent.getPassword()+"===>"+updateStudent.getPassword());
                return "success";
            }
        }
        model.addAttribute("path", "/personalInformation");
        model.addAttribute("msg", "请重新核对填写信息是否正确，进行修改正确后再提交申诉！");
        return "fail";
    }


/************************************************************************************/
/************************************************************************************/

    /**************
     ****首页展示****
     **************/
    @GetMapping("/home")
//    @ResponseBody
    public String home(Model model) {
        switch (number) {
            case 1:
                model.addAttribute("msg_h1", "您好，欢迎登录学生管理系统！");
                model.addAttribute("msg_h3", "本系统向学生提供基本权限，便于学生按需使用系统功能，学生还可以通过系统管理员授权来获取更多功能的使用权限！");
                model.addAttribute("msg_path", "/personalInformation");
//                System.out.println("输出case 1");
                break;
            case 2:
                model.addAttribute("msg_h1", "您好，欢迎登录学生管理系统！");
                model.addAttribute("msg_h3", "本系统向系统管理员提供最大权限，便于系统管理员对系统数据做一定的调整，也方便系统管理员去维护系统，定期更新系统！");
                model.addAttribute("msg_path", "/managementStudent");
//                System.out.println("输出case 2");
                break;
        }
        return "home";
    }
/************************************************************************************/
/************************************************************************************/

    /**************
     ****修改密码****
     **************/
    @GetMapping("/changePassword")
//    @ResponseBody
    public String changePassword(Model model, HttpServletRequest request) {
        Object loginUser = request.getSession().getAttribute("loginUser");
        Object loginUserpw = request.getSession().getAttribute("loginUserpw");
        model.addAttribute("account", (String) loginUser);
        model.addAttribute("user", "?account=" + (String) loginUser + "&password=" + (String) loginUserpw);
        return "changePassword";
//    return (String) loginUser+(String) loginUserpw;
    }

    @PostMapping("/changePassword/validate")
//    @ResponseBody
    public String changePasswordValidate(HttpServletRequest request, @RequestParam("newPassword1") String
            newPassword1, @RequestParam("newPassword2") String newPassword2, @RequestParam("oldPassword") String
                                                 oldPassword, Model model) {
        Object loginUser = request.getSession().getAttribute("loginUser");
        String stuid = (String) loginUser;
        if (studentService.validateLogin(stuid, oldPassword) && newPassword1.equals(newPassword2)) {
            Student student = studentService.selectStudentById(stuid);
            student.setPassword(newPassword1);
            studentService.updateStudent(student);
            model.addAttribute("path", "/");
            model.addAttribute("msg", "密码修改成功，请点击返回重新登录系统！！！");
            return "success";
        }
        model.addAttribute("path", "/changePassword");
        model.addAttribute("msg", "密码修改失败，请确保原密码正确且两次输入的新密码一致！");
        return "fail";
    }
/************************************************************************************/
/************************************************************************************/

    /**************
     ****忘记密码****
     **************/
    @GetMapping("/forgotPassword")
//    @ResponseBody
    public String forgotPassword() {
        return "forgotPassword";
    }

    @GetMapping("/forgotPassword/validate")
//    @ResponseBody
    public String forgotPasswordValidate(@RequestParam("email") String email, @RequestParam("account") String account, Model model) {
        Student student = studentService.selectStudentById(account);
        if (student != null && email != null && adminService.insertRequest(new Request(student.getStuid(), student.getName(), "忘记密码", new Date(), "正在审核", email))) {
            model.addAttribute("path", "/");
            model.addAttribute("msg", "您的申诉请求已受理，请耐心等待系统回复.申诉请求审核将在提交申诉后的工作日两个小时内开始进行，请注意查看您的邮箱地址，在此期间也请谨防网络诈骗冒充系统管理员进行信息诈骗！！！");
            return "success";
        }
        model.addAttribute("path", "/forgotPassword");
        model.addAttribute("msg", "请重新核对填写信息是否正确，进行修改正确后再提交申诉！");
        return "fail";
    }
/************************************************************************************/
/************************************************************************************/

    /******************
     ******授权管理******
     ******************/
    @GetMapping("/managementPower")
//    @ResponseBody
    public String managementPower(Model model) {
        model.addAttribute("message", studentService.selectStudentByAll());
        return "managementPower";
    }

    @GetMapping("/managementPower/validate1/{stuid}")
//    @ResponseBody
    public String managementPowerValidate1(@PathVariable("stuid") String stuid, Model model) {
        Student student = studentService.selectStudentById(stuid);
        student.setPower("学生管理");
        if (studentService.updateStudent(student))
            return "redirect:/managementPower";
        return "false";
    }

    @GetMapping("/managementPower/validate2/{stuid}")
//    @ResponseBody
    public String managementPowerValidate2(@PathVariable("stuid") String stuid, Model model) {
        Student student = studentService.selectStudentById(stuid);
        student.setPower("成绩管理");
        if (studentService.updateStudent(student))
            return "redirect:/managementPower";
        return "false";
    }

    @GetMapping("/managementPower/validate3/{stuid}")
//    @ResponseBody
    public String managementPowerValidate3(@PathVariable("stuid") String stuid, Model model) {
        Student student = studentService.selectStudentById(stuid);
        student.setPower("没有权限");
        if (studentService.updateStudent(student))
            return "redirect:/managementPower";
        return "false";
    }

    @GetMapping("/managementPower/validate4/{stuid}")
//    @ResponseBody
    public String managementPowerValidate4(@PathVariable("stuid") String stuid, Model model) {
        Student student = studentService.selectStudentById(stuid);
        student.setPower("Excel导出");
        if (studentService.updateStudent(student))
            return "redirect:/managementPower";
        return "false";
    }


/************************************************************************************/
/************************************************************************************/

    /******************
     ******请求审核******
     ******************/
    @GetMapping("/auditRequest")
//    @ResponseBody
    public String auditRequest(Model model) {
        model.addAttribute("message", adminService.selectRequestByAll());
//        model.addAttribute("map",map);
        return "auditRequest";
    }

    @GetMapping("/auditRequest/success/{id}")
//    @ResponseBody
    public String auditRequestSuccess(@PathVariable("id") String id, Model model) {
        if (adminService.updateRequestById(Integer.parseInt(id), "审核通过")) {
            if (staticStudent != null)
                studentService.updateStudent(staticStudent);
            return "redirect:/auditRequest";

        }
        return "false";
    }

    @GetMapping("/auditRequest/fail/{id}")
//    @ResponseBody
    public String auditRequestFail(@PathVariable("id") String id, Model model) {
        if (adminService.updateRequestById(Integer.parseInt(id), "撤销审核"))
            return "redirect:/auditRequest";
        return "false";
    }
/************************************************************************************/
/************************************************************************************/

    /******************
     ******成绩管理******
     ******************/
    @GetMapping("/managementGrade")
//    @ResponseBody
    public String managementGrade(Model model) {
        List<Grade> list = courseList();
        model.addAttribute("message", list);
        return "managementGrade";
    }

    /**************
     ****查询成绩****
     **************/
    @RequestMapping("/managementGrade/select")
//    @ResponseBody
    public String managementGradeSelect(HttpServletRequest request, Model model) {
        String type = request.getParameter("type");
        String content = request.getParameter("content");
        List<Course> courseList = adminService.selectCourseByType(type, content);
        List<Grade> gradeList = courseList();
        if (courseList != null) {
            List<Grade> list = new ArrayList<>();
            for (Grade grade : gradeList) {
                for (Course course : courseList) {
                    if (grade.getStuid().equals(course.getStuid()) && grade.getCourse().equals(course.getCourse()))
                        list.add(grade);
                }
            }
            model.addAttribute("message", list);
        }
        return "managementGrade";
    }

    /******************
     ******添加成绩******
     ******************/
    @RequestMapping("/managementGrade/insert")
//    @ResponseBody
    public String managementGradeInsert(HttpServletRequest request, Model model) {
        if (proxy == 1 || gradePower == 1) {
            String stuid = request.getParameter("stuid");
            String course = request.getParameter("course");
            String grade = request.getParameter("grade");
            if (!stuid.equals("") && !course.equals("") && !grade.equals("")) {
                Course c = new Course(
                        stuid, course, Integer.parseInt(grade)
                );
                if (studentService.selectStudentById(stuid) != null && adminService.insertCourse(c)) {
                    model.addAttribute("path", "/managementGrade");
                    model.addAttribute("msg", "学生成绩信息添加成功！！！");
                    return "success";
                }
            }
            model.addAttribute("path", "/managementGrade");
            model.addAttribute("msg", "学生成绩添加失败，请重新编辑完善并保证编辑信息正确！");
            return "fail";
        } else {
            model.addAttribute("path", "/managementGrade");
            model.addAttribute("msg", "对不起，您的权限不够！!");
            return "fail";
        }
    }

    /******************
     ******修改成绩******
     ******************/
    @GetMapping("/managementGrade/update")
//    @ResponseBody
    public String managementGradeUpdate(@RequestParam("id") String id, @RequestParam("grade") String grade, Model model) {
        if (proxy == 1 || gradePower == 1) {
            Course course = adminService.selectCourseById(Integer.parseInt(id));
            if (course != null) {
                course.setGrade(Integer.parseInt(grade));
                if (adminService.updateCourse(course)) {
                    model.addAttribute("path", "/managementGrade");
                    model.addAttribute("msg", "学生成绩信息修改成功！！！");
                    return "success";
//                return "redirect:/managementGrade";
                }
            }
            model.addAttribute("path", "/managementGrade");
            model.addAttribute("msg", "系统成绩修改功能异常，导致学生课程成绩修改失败！");
            return "fail";
        } else {
            model.addAttribute("path", "/managementGrade");
            model.addAttribute("msg", "对不起，您的权限不够！!");
            return "fail";
        }
    }

    /******************
     ******删除成绩******
     ******************/
    @GetMapping("/managementGrade/delete/{id}")
//    @ResponseBody
    public String managementGradeDelete(@PathVariable("id") String id, Model model) {
        if (proxy == 1 || gradePower == 1) {
            Course course = adminService.selectCourseById(Integer.parseInt(id));
            if (course != null) {
                if (adminService.deleteCourseById(Integer.parseInt(id))) {
                    model.addAttribute("path", "/managementGrade");
                    model.addAttribute("msg", "学生成绩信息修改成功！！！");
                    return "success";
                    //                return "redirect:/managementGrade";
                }
            }
            model.addAttribute("path", "/managementGrade");
            model.addAttribute("msg", "系统成绩删除功能异常，导致学生课程成绩删除失败！");
            return "fail";
        } else {
            model.addAttribute("path", "/managementGrade");
            model.addAttribute("msg", "对不起，您的权限不够！!");
            return "fail";
        }
    }

/************************************************************************************/
/************************************************************************************/
    /**************
     ***导出报表***
     **************/
    @GetMapping("reportExcel/{number}")
    public String report(@PathVariable("number") String number, HttpServletResponse response, Model model) {
        if (proxy == 1 || reportPower == 1) {
            setReport(number, response);
            model.addAttribute("path", "/managementGrade");
            model.addAttribute("msg", "Excel导出成功，默认导出在您当前项目与src同级目录下！！！");
            return "success";
        } else {
            model.addAttribute("path", "/managementGrade");
            model.addAttribute("msg", "对不起，您的权限不够！!");
            return "fail";
        }
    }

/************************************************************************************/
/************************************************************************************/
    /**************
     ***自定义方法***
     **************/
    public static Student redirtRequest(HttpServletRequest request) {
        String stuid = request.getParameter("stuid");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String password = request.getParameter("password");
        String power = request.getParameter("power");
        Student student = new Student().setStuid(stuid).setName(name).setSex(sex).setPassword(password).setPower(power);
        if (!(student.getStuid().equals("") || student.getName().equals("") || student.getSex().equals("") || student.getPassword().equals("") || student.getPower().equals("")))
            return student;
        return null;
    }

    public List<Grade> courseList() {
        List<Grade> list = new ArrayList<>();
        for (Student student : studentService.selectStudentByAll()) {
            List<Course> courseList = adminService.selectCourseById(student.getStuid());
            if (courseList != null) {
                for (Course course : courseList) {
                    Grade grade = new Grade().setStuid(student.getStuid()).setName(student.getName()).setCourse(course.getCourse()).setGrade(course.getGrade()).setId(course.getId());
                    list.add(grade);
                }
            }
        }
        return list;
    }

    public void setReport(String number, HttpServletResponse response) {
        String[] title = null;
        String fileName = null;
        String sheetName = null;
        String[][] content = null;
        switch (number) {
            case "1":
                List<Student> studentList = studentService.selectStudentByAll();
                title = new String[]{"学号", "姓名", "性别", "权限"};
                fileName = "学生信息表" + System.currentTimeMillis() + ".xls";
                sheetName = "学生信息表";
                content = new String[studentList.size()][title.length];
                for (int i = 0; i < studentList.size(); i++) {
                    Student obj = studentList.get(i);
                    content[i][0] = obj.getStuid();
                    content[i][1] = obj.getName();
                    content[i][2] = obj.getSex();
                    content[i][3] = obj.getPower();
                }
                break;
            case "2":
                List<Grade> gradeList = courseList();
                title = new String[]{"学号", "姓名", "课程", "分数"};
                fileName = "学生课程成绩表" + System.currentTimeMillis() + ".xls";
                sheetName = "学生课程成绩表";
                content = new String[gradeList.size()][title.length];
                for (int i = 0; i < gradeList.size(); i++) {
                    Grade obj = gradeList.get(i);
                    content[i][0] = obj.getStuid();
                    content[i][1] = obj.getName();
                    content[i][2] = obj.getCourse();
                    content[i][3] = obj.getGrade().toString();
                }
                break;
            case "3":
                List<Request> requestList = adminService.selectRequestByAll();
                title = new String[]{"序号", "学号", "姓名", "邮箱地址", "问题描述", "状态", "申诉时间"};
                fileName = "学生申诉请求表" + System.currentTimeMillis() + ".xls";
                sheetName = "学生申诉请求表";
                content = new String[requestList.size()][title.length];
                for (int i = 0; i < requestList.size(); i++) {
                    Request obj = requestList.get(i);
                    content[i][0] = obj.getId().toString();
                    content[i][1] = obj.getStuid();
                    content[i][2] = obj.getName();
                    content[i][3] = obj.getEmail();
                    content[i][4] = obj.getProblem();
                    content[i][5] = obj.getStatus();
                    content[i][6] = obj.getDate().toString();
                }
                break;
        }
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.reset();
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}


/************************************************************************************/
/************************************************************************************/

